package com.nowcoder;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

/**
 *给定一些同学的信息（名字，成绩）序列，请你将他们的信息按照成绩从高到低或从低到高的排列,相同成绩都按先录入排列在前的规则处理。
 */
public class SortStudentsByScore {
    String name;
    int score;
    int index;
    static int flag;
    public SortStudentsByScore(String name, int score) {
        this.name = name;
        this.score = score;
    }
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        flag = in.nextInt();
        List<SortStudentsByScore> list = new ArrayList();
        for (int i = 0; i < n; i++) {
            boolean flag = list.add(new SortStudentsByScore(in.next(), in.nextInt()));
        }
        list.sort((SortStudentsByScore a, SortStudentsByScore b)->{
            if(flag == 1) {
                return a.score - b.score;
            }
            return b.score - a.score;
        });
        for (SortStudentsByScore s : list) {
            System.out.println(s.name + " " + s.score);
        }
    }
}
